#!/bin/bash

# make sure error return codes are as expected useful cases
# (e.g. commands to check ruleset state)

global_rc=0

cmd() { # (rc, msg, cmd, [args ...])
	rc_exp=$1; shift

	msg_exp=""
	[ $rc_exp != 0 ] && {
		msg_exp="$1"; shift
	}

	for ipt in iptables ip6tables; do
		msg="$($XT_MULTI $ipt "$@" 2>&1 >/dev/null)"
		rc=$?

		[ $rc -eq $rc_exp ] || {
			echo "---> expected return code $rc_exp, got $rc for command '$ipt $@'"
			global_rc=1
		}

		[ -n "$msg_exp" ] || continue
		msg_exp_full="${ipt}$msg_exp"
		grep -q "$msg_exp_full" <<< $msg || {
			echo "---> expected error message '$msg_exp_full', got '$msg' for command '$ipt $@'"
			global_rc=1
		}
	done
}

EEXIST_F=": File exists."
EEXIST=": Chain already exists."
ENOENT=": No chain/target/match by that name."
E2BIG_I=": Index of insertion too big."
E2BIG_D=": Index of deletion too big."
E2BIG_R=": Index of replacement too big."
EBADRULE=": Bad rule (does a matching rule exist in that chain?)."
#ENOTGT=" v[0-9\.]* [^ ]*: Couldn't load target \`foobar':No such file or directory"
ENOMTH=" v[0-9\.]* [^ ]*: Couldn't load match \`foobar':No such file or directory"
ENOTBL=": can't initialize iptables table \`foobar': Table does not exist"

# test chain creation
cmd 0 -N foo
cmd 1 "$EEXIST" -N foo
# iptables-nft allows this - bug or feature?
#cmd 2 -N "invalid name"

# test chain flushing/zeroing
cmd 0 -F foo
cmd 0 -Z foo
cmd 1 "$ENOENT" -F bar
cmd 1 "$ENOENT" -Z bar

# test chain rename
cmd 0 -E foo bar
cmd 1 "$EEXIST_F" -E foo bar
cmd 1 "$ENOENT" -E foo bar2
cmd 0 -N foo2
cmd 1 "$EEXIST_F" -E foo2 bar

# test rule adding
cmd 0 -A INPUT -j ACCEPT
cmd 1 "$ENOENT" -A noexist -j ACCEPT
# next three differ:
# legacy: Couldn't load target `foobar':No such file or directory
# nft:    Chain 'foobar' does not exist
cmd 2 "" -I INPUT -j foobar
cmd 2 "" -R INPUT 1 -j foobar
cmd 2 "" -D INPUT -j foobar
cmd 1 "$EBADRULE" -D INPUT -p tcp --dport 22 -j ACCEPT

# test rulenum commands
cmd 1 "$E2BIG_I" -I INPUT 23 -j ACCEPT
cmd 1 "$E2BIG_D" -D INPUT 23
cmd 1 "$E2BIG_R" -R INPUT 23 -j ACCEPT
cmd 1 "$ENOENT" -I nonexist 23 -j ACCEPT
cmd 1 "$ENOENT" -D nonexist 23
cmd 1 "$ENOENT" -R nonexist 23 -j ACCEPT

# test rule checking
cmd 0 -C INPUT -j ACCEPT
cmd 1 "$EBADRULE" -C FORWARD -j ACCEPT
cmd 1 "$BADRULE" -C nonexist -j ACCEPT
cmd 2 "$ENOMTH" -C INPUT -m foobar -j ACCEPT
# messages of those don't match, but iptables-nft ones are actually nicer.
# legacy: Couldn't load target `foobar':No such file or directory
# nft:    Chain 'foobar' does not exist
cmd 2 "" -C INPUT -j foobar
# legacy: can't initialize ip6tables table `foobar': Table does not exist (do you need to insmod?)
# nft:    table 'foobar' does not exist
cmd 3 "" -t foobar -C INPUT -j ACCEPT

exit $global_rc
